package appfuse.webapp.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import appfuse.framework.WebvegaBaseAction;
import appfuse.framework.database.SqlCommand;
import appfuse.framework.exceptions.BaseException;
import appfuse.framework.util.TokenUtil;
import appfuse.framework.util.json.*;

public class UserLogin extends WebvegaBaseAction {	
	@Override
	public ActionForward executeAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws BaseException, JSONException, IOException
	{
		
		BufferedReader r = new BufferedReader(new InputStreamReader(request.getInputStream()));
	    String strRet = r.readLine();
		//strRet = "[{mac:\"d8:5d:4c:2d:de:66\"},{mac:\"54:e6:fc:2f:5a:a6\"},{mac:\"e0:05:c5:45:26:3e\"}]";	    
	    JSONObject obj = new JSONObject(strRet);
	    String strUserName = "";
	    if (obj.has("user_name"))
	    	strUserName = obj.get("user_name").toString();
	    String strPwd = "";
	    if (obj.has("pwd"))
	    	strPwd = obj.get("pwd").toString();
	    String strToken = "";
	    if (obj.has("token"))
	    	strToken = obj.get("token").toString();
	    strRet = "";
	    UserInfo userInfo = null;
	    if (strUserName == null ||
	    	strUserName.length() <= 0 ||
	    	isUserExists(strUserName) == false)
	    {
	    	strUserName = TokenUtil.VaildToken(strToken);
	    	if (strUserName == null || strUserName.length() <= 0)
	    		strRet +="{result:-1}";
	    	else
	    		userInfo = loginEx(strUserName);	    	
	    }
	    else
    	{
	    	userInfo = login(strUserName, strPwd);
    	}
	    if (userInfo != null)
    	{
	    	strRet = "{";    	
	    	if (userInfo.getUserName().length() == 0)
	 	    {
	 	    	strRet +="result:0,";
	 	    }
	 	    else
	 	    {
	 	    	if (strToken == null || strToken.length() == 0)
	 	    	{
	 	    		strToken = TokenUtil.makeToken(strUserName);
	 	    	}
	 	    	strRet +="result:1,";
	 	    	strRet +="user_name:\""+strUserName+"\",";
	 	    	strRet +="token:\""+strToken+"\",";
	 	    	strRet +="score:"+userInfo.getScore();
	 	    }
	 	    strRet += "}";
    	}
	    PrintWriter out = response.getWriter();
	    System.out.println(strRet); 
	    out.print(strRet);			
	    return null;
	}
	private boolean isUserExists(String strUserName)
	{
		boolean bRet = false;
		UserInfo userInfo = new UserInfo();
		String sql = "select count(*) as count from users where user_name=\""+strUserName+"\"";		
		System.out.println(sql);
		SqlCommand sqlCommand = new SqlCommand();
		try 
		{
			sqlCommand.setSqlCommand(sql);
			ResultSet rs = sqlCommand.executeQuery();
			if (rs.next()) 
			{						
				if (rs.getInt("count") > 0)
					bRet = true;
			}
			
		} 
		catch (SQLException ex) 
		{
			ex.printStackTrace();
		} 
		finally 
		{
			sqlCommand.close();
			sqlCommand = null;
		}
		return bRet;
	}
	private UserInfo login(String strUserName, String strImei, String strPwd)
	{
		UserInfo userInfo = new UserInfo();
		String sql = "select * from users where user_name = \""+strUserName+"\" and pwd = \""+strPwd+"\"";		
		System.out.println(sql);
		SqlCommand sqlCommand = new SqlCommand();
		try 
		{
			sqlCommand.setSqlCommand(sql);
			ResultSet rs = sqlCommand.executeQuery();
			if (rs.next()) 
			{								
				userInfo.setScore(rs.getInt("score"));
				userInfo.setUserName(rs.getString("user_name"));
			}
		} 
		catch (SQLException ex) 
		{
			ex.printStackTrace();
		} 
		finally 
		{
			sqlCommand.close();
			sqlCommand = null;
		}
		return userInfo;
	}
	private UserInfo loginEx(String strUserName)
	{
		UserInfo userInfo = new UserInfo();
		String sql = "select * from users where user_name = \""+strUserName+"\"";		
		SqlCommand sqlCommand = new SqlCommand();
		try 
		{
			sqlCommand.setSqlCommand(sql);
			ResultSet rs = sqlCommand.executeQuery();
			if (rs.next()) 
			{								
				userInfo.setScore(rs.getInt("score"));
				userInfo.setUserName(rs.getString("user_name"));
			}
		} 
		catch (SQLException ex) 
		{
			ex.printStackTrace();
		} 
		finally 
		{
			sqlCommand.close();
			sqlCommand = null;
		}
		return userInfo;
	}
}
